import { ref, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useMenuStore } from '@/stores/menu'
import { hasPermission } from '@/utils/permission'
import * as menuApi from '@/api/menu'
import { message } from 'ant-design-vue'

export function useMenu() {
  const route = useRoute()
  const router = useRouter()
  const authStore = useAuthStore()
  const menuStore = useMenuStore()
  
  const collapsed = ref(false)
  const currentPath = ref(route.path)
  
  // 获取菜单
  const menus = computed(() => menuStore.menus)
  
  // 当前选中菜单
  const selectedKeys = computed(() => {
    const { path } = route
    return [path]
  })
  
  // 根据路径计算需要展开的菜单
  const calculateOpenKeys = (path: string, menuItems: any[]): string[] => {
    const keys: string[] = []
    
    const findOpenKeys = (items: any[], parentPath = '') => {
      for (const item of items) {
        // 处理路径：如果item.path是相对路径，需要拼接父路径
        let itemPath = item.path
        if (!itemPath.startsWith('/')) {
          itemPath = parentPath ? `${parentPath}/${itemPath}` : `/${itemPath}`
        }
        
        // 检查当前路径是否匹配此菜单项或其子菜单
        if (item.children && item.children.length > 0) {
          // 检查子菜单中是否有匹配的
          const hasMatchingChild = item.children.some((child: any) => {
            let childPath = child.path
            if (!childPath.startsWith('/')) {
              childPath = `${itemPath}/${childPath}`
            }
            // 精确匹配或路径前缀匹配
            return path === childPath || path.startsWith(childPath + '/')
          })
          
          // 如果子菜单匹配，或者当前路径是此菜单项的子路径，则展开
          if (hasMatchingChild || (path.startsWith(itemPath + '/') && path !== itemPath)) {
            keys.push(itemPath)
            findOpenKeys(item.children, itemPath)
          }
        }
      }
    }
    
    findOpenKeys(menuItems)
    return keys
  }
  
  // 当前展开菜单
  const openKeys = computed({
    get() {
      const { path } = route
      
      // 如果路径变化了，重新计算需要展开的菜单
      if (path !== currentPath.value) {
        currentPath.value = path
        
        // 计算当前路径需要展开的菜单
        const autoOpenKeys = calculateOpenKeys(path, menuStore.menus)
        
        // 如果当前路径匹配了某个菜单项，则使用自动计算的展开菜单
        if (autoOpenKeys.length > 0) {
          menuStore.setOpenKeys(autoOpenKeys)
          return autoOpenKeys
        } else {
          // 如果路径不匹配任何菜单，清空所有展开的菜单
          // 这样用户可以手动控制菜单的展开/收起
          menuStore.setOpenKeys([])
          return []
        }
      }
      
      // 路径没变化，使用store中保存的openKeys
      return menuStore.openKeys || []
    },
    set(value) {
      // 当用户手动展开/折叠菜单时，保存状态
      menuStore.setOpenKeys(value)
      currentPath.value = route.path
    }
  })
  
  // 监听路由变化，重置当前路径
  watch(() => route.path, (newPath) => {
    if (newPath !== currentPath.value) {
      currentPath.value = newPath
    }
  })
  
  // 切换菜单折叠状态
  const toggleCollapsed = () => {
    collapsed.value = !collapsed.value
    menuStore.setCollapsed(collapsed.value)
  }
  
  // 菜单跳转
  const handleMenuClick = (path: string) => {
    // 确保系统管理子菜单路径正确
    if (path && !path.startsWith('/') && path.match(/^(user|role|permission)$/)) {
      path = `/system/${path}`;
    }
    router.push(path)
  }
  
  // 根据权限过滤菜单
  const filterMenusByPermission = (menus: any[]) => {
    return menus.filter(menu => {
      // 检查菜单权限
      if (menu.permission && !hasPermission(menu.permission)) {
        return false
      }
      
      // 递归处理子菜单
      if (menu.children && menu.children.length > 0) {
        const filteredChildren = filterMenusByPermission(menu.children)
        menu.children = filteredChildren
        
        // 如果子菜单全部被过滤掉了，也要过滤掉父菜单
        return filteredChildren.length > 0
      }
      
      return true
    })
  }
  
  // 初始化菜单
  const initMenus = async () => {
    try {
      // 从后端获取菜单数据
      const res = await menuApi.getUserMenus()
      if (res && res.length > 0) {
        // 将后端返回的菜单转换为前端可用的格式
        const menus = convertMenus(res)
        
        // 设置菜单
        menuStore.setMenus(menus)
      } else {
        // 如果没有菜单数据，设置空菜单
        menuStore.setMenus([])
      }
    } catch (error) {
      console.error('获取菜单失败:', error)
      message.error('获取菜单失败')
      
      // 设置默认菜单（开发阶段用）
      const defaultMenus = [
        {
          path: '/dashboard',
          name: '仪表盘',
          icon: 'dashboard',
          permission: 'dashboard'
        },
        {
          path: '/system',
          name: '系统管理',
          icon: 'setting',
          permission: 'system',
          children: [
            {
              path: '/system/user',
              name: '用户管理',
              icon: 'user',
              permission: 'system:user'
            },
            {
              path: '/system/role',
              name: '角色管理',
              icon: 'team',
              permission: 'system:role'
            },
            {
              path: '/system/permission',
              name: '权限管理',
              icon: 'safety',
              permission: 'system:permission'
            }
          ]
        },
        {
          path: '/profile',
          name: '个人中心',
          icon: 'user',
          permission: 'profile'
        }
      ]
      
      // 设置默认菜单
      menuStore.setMenus(defaultMenus)
    }
  }
  
  /**
   * 将后端返回的菜单转换为前端可用的格式
   */
  const convertMenus = (routers: any[]) => {
    return routers.map(router => {
      // 修正菜单路径，确保系统管理子菜单的路径正确
      let menuPath = router.path;
      
      // 如果是system:开头的权限，且路径不是以/开头，需要添加/system/前缀
      if (router.name?.startsWith('system:') && !menuPath.startsWith('/')) {
        menuPath = `/system/${menuPath}`;
      }
      
      const menu = {
        path: menuPath,
        name: router.meta?.title || router.name,
        icon: router.meta?.icon || '',
        permission: router.name,
        hidden: router.meta?.hidden || false
      } as any
      
      // 处理子菜单
      if (router.children && router.children.length > 0) {
        menu.children = convertMenus(router.children)
      }
      
      return menu
    })
  }
  
  return {
    menus,
    collapsed,
    selectedKeys,
    openKeys,
    toggleCollapsed,
    handleMenuClick,
    initMenus
  }
}
